package com.bjgov.scoresys.dao;
// default package

import static org.hibernate.criterion.Example.create;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;

import com.bjgov.scoresys.entity.ScoreHistory;
import com.bjgov.scoresys.util.Page;

/**
 * A data access object (DAO) providing persistence and search support for
 * ScoreHistory entities. Transaction control of the save(), update() and
 * delete() operations can directly support Spring container-managed
 * transactions or they can be augmented to handle user-managed Spring
 * transactions. Each of these methods provides additional information for how
 * to configure it for the desired type of transaction control.
 * 
 * @see .ScoreHistory
 * @author MyEclipse Persistence Tools
 */

public class ScoreHistoryDAO extends BaseHibernateDAO {
	private static final Log log = LogFactory
			.getLog(ScoreHistoryDAO.class);
	// property constants
	public static final String PROJECT_ITEM_ID = "projectItemId";
	public static final String DEC_SCORE = "decScore";
	public static final String STANDARD_SCORE = "standardScore";
	public static final String PROJECT_ID = "projectId";
	public static final String TOP_CATE_ID = "topCateId";

	public int save(ScoreHistory transientInstance) {
		log.debug("saving ScoreHistory instance");
		int id = 0;
		try {
			id = (Integer) getSession().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
		return id;
	}

	public void delete(ScoreHistory persistentInstance) {
		log.debug("deleting ScoreHistory instance");
		try {
			getSession().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public ScoreHistory findById(java.lang.Long id) {
		log.debug("getting ScoreHistory instance with id: " + id);
		try {
			ScoreHistory instance = (ScoreHistory) getSession().get(
					"com.bjgov.scoresys.entity.ScoreHistory", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List<ScoreHistory> findByExample(ScoreHistory instance) {
		log.debug("finding ScoreHistory instance by example");
		try {
			List<ScoreHistory> results = (List<ScoreHistory>) getSession()
					.createCriteria("ScoreHistory").add(create(instance))
					.list();
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}
	
	public List<ScoreHistory> findByUserIdProjectId(int userId, int projectId) {
		log.debug("finding ScoreHistory instance findByUserIdProjectId: "
				+ userId + ", " + projectId);
		try {
			String queryString = "from ScoreHistory history where history.user.id=? and history.projectId=?";
			Query queryObject = getSession().createQuery(queryString);
			queryObject.setParameter(0, userId);
			queryObject.setParameter(1, projectId);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("findByUserIdProjectId failed", re);
			throw re;
		}
	}

	public List<ScoreHistory> findByUserIdProjectIdItemId(int userId, int projectId, String projectItemIds) {
		log.debug("finding ScoreHistory instance findByUserIdProjectIdItemId: "
				+ userId + ", " + projectId + "," + projectItemIds);
		try {
			String queryString = "from ScoreHistory history where history.user.id=? and history.projectId=? and history.projectItemId in (" + projectItemIds + ")";
			Query queryObject = getSession().createQuery(queryString);
			queryObject.setParameter(0, userId);
			queryObject.setParameter(1, projectId);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("findByUserIdProjectId failed", re);
			throw re;
		}
	}	
	
	public List<ScoreHistory> findByUserIdProjectIdTopCateId(int userId, int projectId, int topCateId) {
		log.debug("finding ScoreHistory instance findByUserIdProjectIdTopCateId: "
				+ userId + ", " + projectId + "," + topCateId);
		try {
			String queryString = "from ScoreHistory history where history.user.id=? and history.projectId=? and history.topCateId=?";
			Query queryObject = getSession().createQuery(queryString);
			queryObject.setParameter(0, userId);
			queryObject.setParameter(1, projectId);
			queryObject.setParameter(2, topCateId);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("findByUserIdProjectIdTopCateId failed", re);
			throw re;
		}
	}		
	
	public ScoreHistory findByUidPidPitemId(int userId, int projectId, int projectItemId) {
		log.debug("finding ScoreHistory instance findByUidPidPitemId: "
				+ userId + ", " + projectId + "," + projectItemId);
		try {
			String queryString = "from ScoreHistory history where history.user.id=? and history.projectId=? and history.projectItemId=?";
			Query queryObject = getSession().createQuery(queryString);
			queryObject.setParameter(0, userId);
			queryObject.setParameter(1, projectId);
			queryObject.setParameter(2, projectItemId);
			return (ScoreHistory) queryObject.uniqueResult();
		} catch (RuntimeException re) {
			log.error("findByUserIdProjectIdTopCateId failed", re);
			throw re;
		}
	}	
	
	/**
	 * 查询被扣子项次数
	 * @return
	 */
	public String getDecScoreDate()
	{
		String queryString = "select count(history.projectItemId) ,history.projectItemId from ScoreHistory history where history.decScore<>0  group by history.projectItemId order by count(history.projectItemId) desc ";
		Query queryObject = getSession().createQuery(queryString);
		List list = queryObject.list();
		String str1="";
		String str2="";
		for(int i=0;i<list.size();i++)
		{
			Object[] res = (Object[])list.get(i);
			str1+=res[0].toString();
			str2+=res[1].toString();
			if(i<list.size()-1)
			{
				if(i>13)
					break;
				str1+=",";
				str2+=",";
			}
		}
		return str1+"|"+str2;
	}
	
	public List findByProperty(String propertyName, Object value) {
		log.debug("finding ScoreHistory instance with property: "
				+ propertyName + ", value: " + value);
		try {
			String queryString = "from ScoreHistory as model where model."
					+ propertyName + "= ?";
			Query queryObject = getSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List<ScoreHistory> findByProjectItemId(Object projectItemId) {
		return findByProperty(PROJECT_ITEM_ID, projectItemId);
	}

	public List<ScoreHistory> findByDecScore(Object decScore) {
		return findByProperty(DEC_SCORE, decScore);
	}

	public List<ScoreHistory> findByStandardScore(Object standardScore) {
		return findByProperty(STANDARD_SCORE, standardScore);
	}

	public List<ScoreHistory> findByProjectId(Object projectId) {
		return findByProperty(PROJECT_ID, projectId);
	}

	public List<ScoreHistory> findByTopCateId(Object topCateId) {
		return findByProperty(TOP_CATE_ID, topCateId);
	}

	public List findAll() {
		log.debug("finding all ScoreHistory instances");
		try {
			String queryString = "from ScoreHistory";
			Query queryObject = getSession().createQuery(queryString);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public ScoreHistory merge(ScoreHistory detachedInstance) {
		log.debug("merging ScoreHistory instance");
		try {
			ScoreHistory result = (ScoreHistory) getSession().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(ScoreHistory instance) {
		log.debug("attaching dirty ScoreHistory instance");
		try {
			getSession().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(ScoreHistory instance) {
		log.debug("attaching clean ScoreHistory instance");
		try {
			getSession().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}
	
	
	
	@Override
	public int count() {
		log.debug("getScoreHistoryCount");
		try {
			String queryString = "select count(id) from ScoreHistory";
			Query query = getSession().createQuery(queryString);
	        return (Integer) query.iterate().next();
		} catch (RuntimeException re) {
			log.error("getScoreHistoryCount failed", re);
			throw re;
		}
	}

	@Override
	public List getByPage(Page page) throws HibernateException {
		String querySentence = "from ScoreHistory";
		Query query = getSession().createQuery(querySentence);
		// 实现分页功能
		query.setFirstResult(page.getBeginIndex())
		.setMaxResults(page.getEveryPage());
		return query.list();
	}	
}